package com.ttx.zookeeper.lock.raw;


import com.ttx.zookeeper.DefaultWatcher;
import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * 互斥锁
 * @author TimFruit
 * @date 20-2-28 上午9:42
 */
public class RawXLockSample {
    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {

        String connectString="127.0.0.1:2181";

        int timeout=(int)MILLISECONDS.convert(10, SECONDS);


        final ZooKeeper zk=new ZooKeeper(connectString, timeout, new DefaultWatcher(),null);



        String lockPath="/xlock";

        if(zk.exists(lockPath,false)==null){
            zk.create(lockPath, "xlockNode".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }

        XLock xLock=new XLock(zk, lockPath);
        System.out.println("准备获取互斥锁...");
        xLock.lock();
        System.out.println("获取成功...");

        System.out.println("休眠等待30s...");
        TimeUnit.SECONDS.sleep(30);

        System.out.println("释放互斥锁...");
        xLock.unLock();







    }










}
